package net.wicp.tams.common.spring.connector.quartz;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.connector.beans.CusDynaBean;
import net.wicp.tams.common.connector.executor.IBusiApp;
import net.wicp.tams.common.exception.ProjectException;
import net.wicp.tams.common.spring.quartz.JobTaskService;
import net.wicp.tams.common.spring.quartz.bean.ScheduleJob;

@Service(value = "quartz.update")
@Slf4j
@ConditionalOnProperty(name = "common.spring.quartz.enable", havingValue = "true")
public class QuartzUpdate implements IBusiApp {

	@Autowired
	private JobTaskService jobTaskService;

	@Override
	public CusDynaBean exe(CusDynaBean inputBean, CusDynaBean outBeanOri) throws ProjectException {
		Cmd cmd = inputBean.getByType(Cmd.class, "cmd");
		Integer id = inputBean.getByType(Integer.class, "id");
		String cronExpression = inputBean.getStrValueByName("cronExpression");
		ScheduleJob addobj = new ScheduleJob();
		addobj.setId(Long.valueOf(String.valueOf(id)));
		addobj.setCronExpression(cronExpression);
		try {
			switch (cmd) {
			case start:
			case stop:
				jobTaskService.changeStatus(addobj.getId(), cmd.name());
				break;
			case cron:
				jobTaskService.updateCron(addobj.getId(), addobj.getCronExpression());
				break;
			default:
				break;
			}
			outBeanOri.setResult(Result.getSuc());
		} catch (Exception e) {
			log.error("更新job错误", e);
			outBeanOri.setResult(Result.getError(e.getMessage()));
		}
		return outBeanOri;
	}
}
